<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { showFailToast, showLoadingToast, closeToast } from 'vant'

interface PriceItem {
  priceId: number
  medicine: string
  price: number
  specifications: string
  manufacturer: string
  medicalinsurance: boolean
  item: string
  // 以下字段用于显示额外信息
  itemType?: string // 项目类型
  sampleType?: string // 样本类型
}

interface ApiResponse {
  mes: string
  code: number
  data: PriceItem[]
}

const router = useRouter()

// 数据相关
const priceList = ref<PriceItem[]>([])
const filteredList = ref<PriceItem[]>([])
const loading = ref(false)
const finished = ref(false)

// 搜索和筛选
const searchKeyword = ref('')
const selectedType = ref('全部类型')
const typeOptions = ref<string[]>(['全部类型'])
const showTypePicker = ref(false)

// 获取价目数据
const fetchPriceList = async () => {
  try {
    loading.value = true
    showLoadingToast({
      message: '加载中...',
      forbidClick: true
    })

    const response = await fetch('http://localhost:5029/api/Health/ShowPrice', {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        'accept': 'text/plain'
      }
    })

    if (!response.ok) {
      throw new Error('网络请求失败')
    }

    const result: ApiResponse = await response.json()

    if (result.code === 300 && result.data && result.data.length > 0) {
      priceList.value = result.data
      
      // 提取类型选项
      const types = Array.from(new Set(result.data.map(item => item.item).filter(Boolean)))
      typeOptions.value = ['全部类型', ...types]
      
      // 初始过滤
      filterData()
    } else {
      priceList.value = []
      filteredList.value = []
      if (result.code !== 300) {
        showFailToast(result.mes || '获取数据失败')
      }
    }
    
    finished.value = true
  } catch (error) {
    console.error('获取价目列表失败:', error)
    priceList.value = []
    filteredList.value = []
    showFailToast('网络请求失败，请检查网络连接')
  } finally {
    loading.value = false
    closeToast()
  }
}

// 过滤数据
const filterData = () => {
  let result = [...priceList.value]
  
  // 按类型过滤
  if (selectedType.value !== '全部类型') {
    result = result.filter(item => item.item === selectedType.value)
  }
  
  // 按关键词搜索
  if (searchKeyword.value.trim()) {
    const keyword = searchKeyword.value.trim().toLowerCase()
    result = result.filter(item => 
      item.medicine.toLowerCase().includes(keyword) ||
      (item.specifications && item.specifications.toLowerCase().includes(keyword)) ||
      (item.manufacturer && item.manufacturer.toLowerCase().includes(keyword))
    )
  }
  
  filteredList.value = result
}

// 搜索处理
const handleSearch = () => {
  filterData()
}

// 类型选择处理
const handleTypeChange = (type: string) => {
  selectedType.value = type
  filterData()
}

// 获取标签颜色
const getItemTagColor = (item: string) => {
  const colorMap: Record<string, string> = {
    '药品': '#87CEEB', // 浅蓝色
    '诊疗': '#87CEEB', // 浅蓝色
    '检查': '#FFB6C1' // 浅粉色
  }
  return colorMap[item] || '#FFA500' // 默认浅橙色
}

// 初始化
onMounted(() => {
  fetchPriceList()
})
</script>

<template>
  <div class="price-list-view">
    <!-- 导航栏 -->
    <van-nav-bar
      title="价目查询"
      left-text=""
      left-arrow
      @click-left="router.back()"
      class="nav-bar"
    >
      <template #right>
        <van-icon name="ellipsis" size="18" />
        <van-icon name="cross" size="18" style="margin-left: 12px" />
      </template>
    </van-nav-bar>

    <!-- 搜索栏 -->
    <div class="search-section">
      <div class="search-wrapper">
        <van-icon name="search" class="search-icon" />
        <input
          v-model="searchKeyword"
          type="text"
          placeholder="可输入药品、项目内容"
          class="search-input"
          @input="handleSearch"
        />
      </div>
      <div class="type-selector" @click="showTypePicker = true">
        <span>{{ selectedType }}</span>
        <van-icon name="arrow-down" size="12" />
      </div>
    </div>

    <!-- 类型选择器（临时实现为下拉） -->
    <div v-if="showTypePicker" class="type-picker-overlay" @click="showTypePicker = false">
      <div class="type-picker" @click.stop>
        <div
          v-for="type in typeOptions"
          :key="type"
          class="type-option"
          :class="{ active: selectedType === type }"
          @click="handleTypeChange(type); showTypePicker = false"
        >
          {{ type }}
        </div>
      </div>
    </div>

    <!-- 价目列表 -->
    <div class="list-section">
      <div v-if="loading && filteredList.length === 0" class="loading-state">
        加载中...
      </div>
      
      <div v-else-if="filteredList.length === 0" class="empty-state">
        暂无数据
      </div>

      <div v-else class="price-list">
        <div
          v-for="item in filteredList"
          :key="item.priceId"
          class="price-item"
        >
          <div class="item-content">
            <div class="item-header">
              <h3 class="item-title">{{ item.medicine }}</h3>
              <span
                class="item-tag"
                :style="{ backgroundColor: getItemTagColor(item.item) }"
              >
                {{ item.item }}
              </span>
            </div>
            
            <div class="item-details">
              <div class="detail-row">
                <span class="detail-label">价格:</span>
                <span class="detail-value price">{{ item.price.toFixed(2) }}(元)</span>
              </div>
              
              <!-- 药品类型显示规格和厂家 -->
              <template v-if="item.item === '药品'">
                <div v-if="item.specifications" class="detail-row">
                  <span class="detail-label">规格:</span>
                  <span class="detail-value">{{ item.specifications }}</span>
                </div>
                
                <div v-if="item.manufacturer" class="detail-row">
                  <span class="detail-label">生产厂家:</span>
                  <span class="detail-value">{{ item.manufacturer }}</span>
                </div>
                
                <div class="detail-row">
                  <span class="detail-label">是否医保:</span>
                  <span class="detail-value">{{ item.medicalinsurance ? '是' : '否' }}</span>
                </div>
              </template>
              
              <!-- 诊疗类型 -->
              <template v-else-if="item.item === '诊疗'">
                <div v-if="item.medicalinsurance !== undefined" class="detail-row">
                  <span class="detail-label">是否医保:</span>
                  <span class="detail-value">{{ item.medicalinsurance ? '是' : '否' }}</span>
                </div>
              </template>
              
              <!-- 检查类型显示项目类型和样本类型 -->
              <template v-else-if="item.item === '检查'">
                <div v-if="item.specifications" class="detail-row">
                  <span class="detail-label">项目类型:</span>
                  <span class="detail-value">{{ item.specifications }}</span>
                </div>
                <div v-if="item.manufacturer" class="detail-row">
                  <span class="detail-label">样本类型:</span>
                  <span class="detail-value">{{ item.manufacturer }}</span>
                </div>
              </template>
              
              <!-- 其他类型显示所有可用信息 -->
              <template v-else>
                <div v-if="item.specifications" class="detail-row">
                  <span class="detail-label">规格:</span>
                  <span class="detail-value">{{ item.specifications }}</span>
                </div>
                <div v-if="item.manufacturer" class="detail-row">
                  <span class="detail-label">生产厂家:</span>
                  <span class="detail-value">{{ item.manufacturer }}</span>
                </div>
              </template>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 上拉加载更多提示 -->
    <div v-if="filteredList.length > 0 && !loading" class="load-more">
      上拉加载更多
    </div>
  </div>
</template>

<style scoped>
.price-list-view {
  width: 100%;
  min-height: 100vh;
  background-color: #f7f8fa;
}

.nav-bar {
  background-color: #fff;
}

.search-section {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px 16px;
  background-color: #fff;
  border-bottom: 1px solid #ebedf0;
}

.search-wrapper {
  flex: 1;
  position: relative;
  background-color: #f7f8fa;
  border-radius: 4px;
  padding: 8px 12px;
  display: flex;
  align-items: center;
}

.search-icon {
  color: #969799;
  margin-right: 8px;
}

.search-input {
  flex: 1;
  border: none;
  outline: none;
  background: transparent;
  font-size: 14px;
  color: #323233;
}

.search-input::placeholder {
  color: #c8c9cc;
}

.type-selector {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 8px 12px;
  background-color: #f7f8fa;
  border-radius: 4px;
  font-size: 14px;
  color: #323233;
  cursor: pointer;
}

.type-picker-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.3);
  z-index: 1000;
  display: flex;
  align-items: flex-start;
  justify-content: center;
  padding-top: 100px;
}

.type-picker {
  background-color: #fff;
  border-radius: 8px;
  width: 90%;
  max-width: 300px;
  max-height: 400px;
  overflow-y: auto;
}

.type-option {
  padding: 12px 16px;
  font-size: 14px;
  color: #323233;
  cursor: pointer;
  border-bottom: 1px solid #ebedf0;
}

.type-option:last-child {
  border-bottom: none;
}

.type-option.active {
  color: #1989fa;
  background-color: #f0f8ff;
}

.type-option:active {
  background-color: #f7f8fa;
}

.list-section {
  padding: 8px 16px;
}

.loading-state,
.empty-state {
  text-align: center;
  padding: 40px 20px;
  color: #969799;
  font-size: 14px;
}

.price-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.price-item {
  background-color: #fff;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 8px;
}

.item-content {
  position: relative;
}

.item-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 12px;
}

.item-title {
  flex: 1;
  font-size: 16px;
  font-weight: bold;
  color: #323233;
  margin: 0;
  margin-right: 12px;
  line-height: 1.4;
}

.item-tag {
  padding: 4px 12px;
  border-radius: 12px;
  font-size: 12px;
  color: #fff;
  white-space: nowrap;
  flex-shrink: 0;
}

.item-details {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.detail-row {
  display: flex;
  align-items: center;
  font-size: 14px;
}

.detail-label {
  color: #646566;
  margin-right: 8px;
  white-space: nowrap;
}

.detail-value {
  color: #323233;
}

.detail-value.price {
  color: #ee0a24;
  font-weight: 500;
}

.load-more {
  text-align: center;
  padding: 16px;
  color: #969799;
  font-size: 12px;
}
</style>
